<?php
/**********************************************************************************
 
	Lists sales of a given item
 
 	Copyright (C) 2010 Benjamin Thomas
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 	Author: Benjamin Thomas
	Email: thomas.ben@gmail.com
	Created: 05.21.10
 	Revised: 

	Inputs: graph_limit - Number of days to display on graph (default is 7)
			item - Item to search for
 	Calls: None.
 
 **********************************************************************************
 */
 
require_once(dirname(__FILE__) . '/../../lib/PageLayout.php');
require_once(dirname(__FILE__) . '/../../lib/MarketDB.php');
require_once(dirname(__FILE__) . '/../../lib/dateFunctions.php');
require_once(dirname(__FILE__) . '/../../lib/Recipe.php');

$graph_limit = 14;
$graph_limit_max = 30;
$table_limit = 7000;
$graph_limit_accept = array(7, 14, 30);

if (array_key_exists('limit', $_GET)) {
	$_GET['limit'] = intval($_GET['limit']);
	if ( !in_array($_GET['limit'],$graph_limit_accept) ) {
		$graph_limit = 14;
	} elseif ($_GET['limit'] > $graph_limit_max) {
		$graph_limit = $graph_limit_max;
	} else {
		$graph_limit = $_GET['limit'];
	} 
}
if (array_key_exists('id', $_GET)) {
	$id = intval($_GET['id']);
} else {
	include("index.php");
	//echo "No itemId supplied. Exiting.";
	exit();
}
if (array_key_exists('p', $_GET)) {
	$page = intval($_GET['p']);
} else {
	$page = 1;
}


// Instance a new Database
$marketDB = new MarketDB();
$marketDB->loadItems();
$item = $marketDB->getItem($id);
$auctions = $marketDB->getSales($graph_limit, $id);
$tableData = array();
for ($i = 0; $i < count($auctions); $i++) {
	$val = $auctions[$i];
	$temp = array();
	$temp[0] = date("n/j/y g:i a", $val['time']);
	$temp[1] = date("l", $val['time']);
	$temp[2] = utf8_encode($val['buyer']);
	$temp[3] = $val['stackCount'];
	$temp[4] = getGold(floor($val['money'] / $val['stackCount'])); 
	$tableData[] = $temp;
}

$day = date("j", time()); $month = date("n", time()); $year = date("Y", time());
$start = mktime(0,0,0, $month, $day - ($graph_limit + 1), $year);
$sales=$marketDB->getSalesDataByDay($start, 0, $id);

if (!$icon = $item['icon']) {
	$icon = "404.png";
}
$icon = '<img src="images/icons/'. $icon . '" style="height:20px; width: 20px; margin-right: 5px;" />';
echo '<div style="margin-top: 20px;" class="btn" id="btngraph">' . $icon . ' ' . $item['name'] . '<br /></div>';
$top = array();
$top[] = "<a href='#' onClick='showSales($graph_limit)' class='small'><< Sales List</a>";
if ($graph_limit != 7) { $top[] = "<a href='#limit=7&id=$id' onClick='showSales(7, $id)' class='small'>Last 7 Days</a>"; }
if ($graph_limit != 14) { $top[] = "<a href='#limit=14&id=$id' onClick='showSales(14, $id)' class='small'>Last 14 Days</a>"; }
if ($graph_limit != 30) { $top[] =  "<a href='#limit=30&id=$id' onClick='showSales(30, $id)' class='small'>Last 30 Days</a>"; }
$top[] = "<a href='#limit=14&id=$id' onClick='showScans($graph_limit, $id)' class='small'>Scans</a>";
echo  implode(" | ", $top);
unset($top);
print "<hr />";
print '<div id="placeholder" class="graph" style="width:900px;height:300px; text-align:center">';
print "<img src='images/indicator.gif' style='margin-left: auto; margin-right: auto' alt='loading...' />";
print '<br />Your graph is loading.</div>' . "\n\n";


printCraftable($id);

$headings = array("Time", "Day", "Buyer", "Return", "Rate");
echo '<div style="margin-top: 20px;"  class="btn" id="btnsales">Sales Data<br /><hr /></div>';
echo '<div id="sales">';
?>
<div id="pager" class="pager" style="text-align:right; magin-top: 10px; margin-bottom: -15px;"> 
	<form> 
		<img src="images/first.png" class="first"/> 
		<img src="images/prev.png" class="prev"/>
		<span style="color: black" class="pagedisplay"></span>
		<img src="images/next.png" class="next"/> 
		<img src="images/last.png" class="last"/> 
		<select class="pagesize"> 
			<option  value="10">10</option> 
			<option selected="selected"  value="20">20</option> 
			<option value="30">30</option> 
			<option  value="40">40</option> 
		</select> 
	</form> 
</div> 
<?php
echo '<table id="salesdata" class="tablesorter">' . "\n";
echo '<thead>' . "\n";
echo '<tr>' . "\n";
echo '<th>Time</th><th>Day</th><th>Buyer</th><th style="width: 40px;">Qty</th><th style="width: 100px;">Rate</th>' . "\n";
echo '</tr>' . "\n";
echo '</thead>' . "\n";
echo '<tbody>' . "\n";
if (!count($tableData)) {
	echo '</tbody></table>';
	echo '<div style="width: 300px; text-align:center; margin-left: auto; margin-right: auto;">No results found</div>';
} else {
	foreach($tableData as &$row) {
		echo '<tr>';
		foreach($row as &$val) {
			if (!$val) { $val = "&nbsp;"; }
			echo '<td> ' . $val . ' </td>';
		}
		echo '</tr>' . "\n";
	}
	echo '</tbody>' . "\n";
	echo '</table>' . "\n";
}
echo '</div>';


$dailyCounts = createTimestampArray($graph_limit,0);
$dailyFreq = createTimestampArray($graph_limit,0);
$dailyMin = createTimestampArray($graph_limit,0);
$dailyMax = createTimestampArray($graph_limit,0);
$summary = $marketDB->getSalesSummary($graph_limit, $id);

foreach($summary as &$row) {
	$i = array_search(array(strtotime($row['day']) * 1000,0), $dailyCounts);
	$dailyCounts[$i][1] = $row['money'] / 10000;
	$dailyFreq[$i][1] = $row['total'];
	$dailyMin[$i][1] = $row['min'] / 10000;
	$dailyMax[$i][1] = $row['max'] / 10000;
}
?>

<script id="source" language="javascript" type="text/javascript">
$(function () {
	$('#btnsales').bind('click', function() { fadeToggle("#sales"); });
	$('#btngraph').bind('click', function() { fadeToggle("#placeholder"); });
	$('#btncraft').bind('click', function() { fadeToggle("#craft"); });
	$('#placeholder').bind('click', function() { $(".legend").toggle(); });
	var rd = [];
	rd[0] = <?php echo json_encode($dailyMin); ?>;
	rd[1] = <?php echo json_encode($dailyMax); ?>;
	rd[2] = <?php echo json_encode($dailyCounts); ?>;
	rd[3] = <?php echo json_encode($dailyFreq); ?>;
	for (var j = 0; j < rd.length; ++j)
		for (var i = 0; i < rd[j].length; ++i)
			rd[j][i][0] +=  <?php echo getOffset(); ?> * 1000;
 
    var options = {
        xaxis: { mode: "time", timeformat: "%m/%d" },
		yaxes: [
			{ position: 'left' },
			{ position: 'left' },
			{ position: 'right' },
		],
		yaxis: { min: 0 },
		legend: { position: 'nw' },
		grid: { hoverable: true }
    };
	
	var d = [
		{ data: rd[3], type: 'int', label: "Completed Auctions", color: "rgb(175,216,248)", yaxis: 3, bars: { show: true, align: 'center', barWidth: 60*60*24*1000 }, lines: { show: false } },
		{ data: rd[0], type: 'gold', tooltip: 'Min Sale Price', label: 'Sale Price', id: 'salemin', color: "rgb(77,167,77)", lines: { show: true } },
		{ data: rd[1], type: 'gold', tooltip: 'Max Sale Price', lines: { show: true, fill: 0.25 }, color: "rgb(77,167,77)", fillBetween: 'salemin' },
		{ data: rd[2], type: 'gold', label: 'Gold Earned', yaxis: 2, lines: { show: true } }

	]
	
    var plot = $.plot($("#placeholder"), d, options);

    var previousPoint = null;
	var monthname=new Array("January","February","March","April","May","June","July","August","September","Octber","November","December");
    $("#placeholder").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));
 
		if (item) {
			if (previousPoint != item.datapoint) {
				previousPoint = item.datapoint;
				
				$("#tooltip").remove();
				var x = new Date(item.datapoint[0]);
				x = monthname[x.getMonth()] + " " + x.getDate();
				var y = item.datapoint[1];
				showToolTip(item, x, y);
			}
		}
		else {
			$("#tooltip").remove();
			previousPoint = null;            
		}
    });   
	$('.legendColorBox').live('click', function() {
		var s =  $(this).siblings().text(); 
		if (s == 'Completed Auctions')
			d[0]['bars']['show'] = !d[0]['bars']['show'];
		if (s == 'Sale Price') {
			d[1]['lines']['show'] = !d[1]['lines']['show'];
			d[2]['lines']['show'] = !d[2]['lines']['show'];
		}
		if (s == 'Gold Earned')
			d[3]['lines']['show'] = !d[3]['lines']['show'];
		var plot = $.plot($("#placeholder"), d, options);	
	});
});
</script> 
<script>
$(document).ready(function() 
    {   
		$.tablesorter.addParser({ 
        id: 'gold', 
        is: function(s) { 
            return false; 
        }, 
        format: function(s) {
			var val = 0;
			var tmp = s.match( /(\d*)<img.*gold/ );	if (tmp) { val += (tmp[1] *  10000); }
			var tmp = s.match( /(\d*)<img.*silver/ );	if (tmp) { val += (tmp[1] *  100); }
			var tmp = s.match( /(\d*)<img.*copper/ );	if (tmp) { val += tmp[1]; }
			return val;
        }, 
        type: 'numeric' 
		}); 
	$.tablesorter.addParser({ 
		id: 'weekday', 
		is: function(s) { 
			return false; 
		}, 
		format: function(s) {
			var val = 0;	
			switch (s) {
				case ' Sunday ': val =  1; break;
				case ' Monday ': val = 2; break;
				case ' Tuesday ': val = 3; break;
				case ' Wednesday ': val = 4; break;
				case ' Thursday ': val = 5; break;
				case ' Friday ': val = 6; break;
				case ' Saturday ': val = 7; break;
			}
			return val;
		}, 
		type: 'numeric' 
	}); 	
	$(function() { 
        $("#salesdata").tablesorter({ 
			sortList: [[0,1]],
            headers: { 
				1: { sorter:'weekday' },
				4: { sorter:'gold' }
            },
			widthFixed: true,
			widgets: ['zebra']			
        }); 
		$("#salesdata").tablesorterPager({container: $("#pager")});
    });      

    } 
); 
</script>


<?php
function printCraftable($id) {
	$db = $GLOBALS['marketDB'];
	$db->loadProfessions();
	$empty = "X";
	$unknown = "?";
	
	$sql = "SELECT * FROM crafting WHERE productID = $id";
	$result = $db->publicQuery($sql);
	
	if ($result) {
		echo '<div style="margin-top: 20px;" class="btn" id="btncraft">Crafted From<br /><hr /></div>';
		echo '<div id="craft">';
		echo '<table class="tablesorter">';
		echo '<thead><tr>';
		echo '<th>Profession</th><th>Recipe</th><th>Crafting<BR>Cost</th><th>Est. Yield</th>';
		echo '</tr></thead>';
		
		foreach($result as $row) {
			$recipe = new Recipe($row['craftID'],$db);
			$recipe->minimizeCosts();
			printRecipe($recipe->toArray());
			unset($recipe);	
		}
	
		echo "</tbody></table>";		
		echo "</div>";
	}
	
/*
		echo '<div style="margin-top: 20px;" class="btn" id="btncraft">Crafted From<br /><hr /></div>';
		echo '<div id="craft">';
		echo '<table class="tablesorter">';
		echo '<thead><tr>';
		echo '<th>Item</th><th>Qty</th><th>Vendor</th><th>Purchase<BR>Average</th><th>Market<br>Average</th>';
		echo '<th>Bottom 15<sup>th</sup> Percentile<BR>Average</th><th>Crafting<BR />(Purchase Average)</th><th>Crafting<br />(Market Average)</th>';
		echo '</tr></thead>';
		echo '<tfoot><tr>';
		echo '<td>Total*</td>';
		echo '<td>' . $out . '</td>';
		echo '<td>' . $totals['vendor'] . '</td>';
		echo '<td>' . $totals['buyavg'] . '</td>';
		echo '<td>' . $totals['markavg'] . '</td>';
		echo '<td>' . $totals['fifperc'] . '</td>';
		echo '<td>' . $totals['craftbuyavg'] . '</td>';	
		echo '<td>' . $totals['craftmarkavg'] . '</td>';	
		echo '</tr></tfoot>';

		echo '<tbody>';
		foreach($crafttable as &$row) {
			echo '<tr>';
			foreach($row as &$val) {
				echo '<td>' . $val . '</td>';
			}
			echo '</tr>';
		}
		echo '</tbody></table>';
		echo '</div>';
	}
*/
}

function printRecipe(&$tree, $prefix = '') {
	$db = &$GLOBALS['marketDB'];
	$item = &$db->items[$tree['id']];
	
	
	echo '<tr>' . "\n";
	$prof = $db->getProfession($tree['prof']);
	echo '<td><img src="images/icons/' . $prof['icon'] . '" style="width:20px; height: 20px;" /></td>';
	echo '<td>' . $prefix;
	$link = '<a href="#' . $tree['cid'] . '" onClick="showRecipe(' . $tree['cid'] . ')">' . $item['name'] . '</a>';
	echo '<img src="images/icons/' . $item['icon'] . '" style="width:20px; height: 20px;" /> ' . $link . '</td>';
	if ($tree['in']) { $t = $tree['in']; }  else { $t = 1; }
	$vf = ($tree['price'] * $t);
	if (array_key_exists('cost', $tree)) {
		$vi = $tree['cost'];
		echo '<td>' . getGold($vi) . '</td>';
		echo '<td>' . round(safediv($vf - $vi,$vi)*100) . '%</td>';
	}
	echo '</tr>' . "\n";
	unset($item);
}

function getCraftable($id, &$market, &$craftData = array(), $mul = 1, $allowIgnored = 1) {	
	$inputs = $market->getCraftableInputs($id, $allowIgnored);
	foreach ( $inputs as &$val) {
		$item = $val['name'];
		$count = $val['inputCount'];
		$cID = $val['inputID'];
		$price = $val['price'];
		if (0 && $market->isCraftable($val['inputID'],0)  ) {
			$craftData = getCraftable( $val['inputID'] , $market, $craftData, $val['inputCount'], 0);
		} else {
			if (!$price) {
				$link = '<a href="itemScans.php?id=' . $cID . '">' . $item . '</a>';
			} else {
				$link = $item;				
			}
			
			$craftData[] = array('id' => $cID, 'count' => $count, 'price' => $price, 'name' => $item );
		}
	}
	return $craftData;
}
?>